import { defineStore} from 'pinia'
import {reqLogin,getUserInfo} from "@/api/user";
import {loginForm} from "@/api/user/type.ts";
//引入路由
import { routes } from '@/router/routes.ts'
import {UserState} from "@/store/modules/type.ts";
import {setToken,getToken,removeToken} from '@/utils/token.ts'

const useUserStore = defineStore('User', {
  //存储数据
  state:(): UserState =>{
    return {
      token: getToken(),
      menuRoutes: routes,
      username: '',
      avatar: '',
    }
  },
  //处理逻辑
  actions:{
    async userLogin(data:loginForm){
      const loginRes = await reqLogin(data);
      if(loginRes.code === 200){
        setToken(loginRes.data.token)
        this.token = loginRes.data.token
        return 'ok'
      }else {
        return Promise.reject(new Error(loginRes.message))
      }
    },
    async userInfo(){
      const result = await getUserInfo();
      console.log(result)
      if(result.code == 200 ){
        console.log(result.data)
        this.username = result.data.username;
        this.avatar = result.data.avatar;
      }else{
        console.log(result)
        return Promise.reject(new Error(result.message))
      }
    },
    async userLogout(){
      this.token = ''
      this.username = ''
      this.avatar = ''
      removeToken()
    }
  },
  //计算属性
  getters:{

  }
})

export default useUserStore
